﻿using System;
using System.Security;
using System.Security.Permissions;
using System.Web.Security;
using Omniscient.Foundation.ApplicationModel;
using Omniscient.Foundation.Logging;
using Omniscient.Foundation.Security;
using Omniscient.TimeTracker.BusinessModel.Security;

namespace Omniscient.TimeTracker.Server
{
    public class SecurityService : ISecurityService
    {
        private ILogger _logger;
        public SecurityService()
        {
            ILoggingService service;
            service = ApplicationManager.Current.ServiceProvider.GetService<ILoggingService>();
            if (service == null) return;
            _logger = service.GetLogger(this.GetType());
        }

        private void LogDebug(object message)
        {
            if (_logger == null) return;
            _logger.Debug(message);
        }

        #region ISecurityServiceContract Members

        [PrincipalPermission(SecurityAction.Demand, Authenticated = false)]
        public SecurePrincipal GetAuthenticatedUser(string username, string password)
        {
            LogDebug(string.Format("Entering GetAuthenticatedUser..."));

            if (string.IsNullOrEmpty(username))
                throw new ArgumentNullException("username");
            if (string.IsNullOrEmpty(password))
                throw new ArgumentNullException("password");

            bool valid = Membership.ValidateUser(username, password);
            if (!valid)
            {
                throw new InvalidOperationException("Username and/or password are not valid. Authentication failed.");
            }   

            SecureString securePassword;
            securePassword = SecureStringConverter.ToSecureString(password);

            SecureIdentity identity;
            identity = new SecureIdentity(username, securePassword);

            IRoleProvider roleProvider;
            roleProvider = ApplicationManager.Current.ObjectContainer.Get<IRoleProvider>();
            if (roleProvider == null) throw new InvalidOperationException("Can't find IRoleProvider instance in the container.");

            string[] roles;
            roles = roleProvider.GetRolesForUser(username);

            SecurePrincipal principal;
            principal = new SecurePrincipal(identity, roles);

            return principal;
        }

        #endregion
    }
}
